<?php
namespace Home\Controller;

use Utuo\ForegroundController;

class UserController extends ForegroundController {
	
	public function _init() {
		$this->modelName = cookie("model");
		layout("user");
	}
	
	public function registerAction() {
		$this->setPageTitle('用户注册');
		$this->display();
	}
	
	public function loginAction() {
		$this->setPageTitle('用户登录');
		$this->display();
	}
	
	// 修改信息
	public function modifyPostAction() {
		C('TOKEN_ON', false);
		$this->checkLogin();
		$m = M("User");
		$oldPassword = I("old_password");
		if($m->field("nick_name,password")->create()) {
			empty($m->nick_name) and $this->ajaxError("昵称不能为空");
			if(empty($m->password)) unset($m->password);
			else {
				$password = $m->where("id=%d", $this->uid)->getField("password");
				hash_pwd($oldPassword) === $password and $m->password = hash_pwd($m->password) or $this->ajaxError("原始密码输入不正确!");
			}
			false !== $m->where("id=%d", $this->uid)->save() and $this->ajaxSuccess("保存成功");
		}
		$this->ajaxError($m->getError());
	}
	
	// 用户注册
	public function registerPostAction() {
		$d = D("UserAssociation");
		$dUser = D("My/User", "Model");
		if($dUser->create()) {
			if($id = $dUser->add() and $d->uid = $id) {
				$d->cid = $this->sid;
				$sponsor_name = I("sponsor_name") and $d->sponsor_name = $sponsor_name; // 推荐人 
				$sponsor_tel = I("sponsor_tel") and $d->sponsor_tel = $sponsor_tel; // 推荐人电话
				$d->add();
				$this->ajaxSuccess();
			} else {
				$this->ajaxError($dUser->getError());
			}
		}
		$this->ajaxError($dUser->getError());
	}
	
	// 用户登录
	public function loginPostAction() {
		$name = I("name", "");
		$password = I("password", "");
		$m = M("User");
		$mUserAssociation = M("UserAssociation");
		$user = $m->where(array('name'=>$name))->find();
		if($user) {
			if(\Utuo\Phpass::check($password, $user['password'])) {				/*该用户是否在该商家已激活过*/
				$condition = array('uid'=>$user["id"], 'cid'=>$this->sid);
				$userAssociation = $mUserAssociation->where($condition)->find();
				if(!$userAssociation) { // 从未登录则立即激活
					$mUserAssociation->add($condition);
					$userAssociation = $mUserAssociation->where($condition)->find() or $this->ajaxError("未能登录该应用，激活失败");
				}
				$user = array_merge($user, array(
					'is_deleted' => $userAssociation['is_deleted'],
					'status' => $userAssociation['status'],
					'cid' => $userAssociation['cid'],
				));
				/*保存会话*/
				if($user['status'] and !$user['is_deleted']) {
					session("user", array(
						'id' => $user['id'],
						'name'=> $user['name'],
					));
					session('id', $user['id']);
					/*保存用户在系统的登录信息*/
					$adminData = array(
							'last_login_time' => time(),
							'last_login_ip' => get_client_ip(),
							'login_count' => $user['login_count'] + 1
					);
					M('User')->where("id=" . $user['id'])->save($adminData);
					/*保存用户在商家的登录信息*/
					$adminData['login_count'] = $userAssociation['login_count'] + 1;
					M('UserAssociation')->where(array(
						'cid' => $this->sid,
						'uid' => $user['id'],
					))->save($adminData);
					\Utuo\Score::exec($this->cid, "USER_LOGIN"); // 积分处理
					$this->ajaxSuccess( "登录成功." );
				} 
				$this->ajaxError( "您的账户已被当前店家删除或禁用."  );
			} else {
				$this->ajaxError("密码错误");
			}
		}
		$this->ajaxError("用户不存在");
	}
	
	
	// 登出
	public function logoutAction() {
		$backUrl = I("back_url");
		session('user', null);
		session('cart', null);
		session('order', null);
		$this->success("已安全退出.", $backUrl);
	}
	
	// 用户签到
	public function signInAction() {
		$this->checkLogin();
		$result = \Utuo\Score::exec($this->cid, "USER_SIGN_IN", array(
				'r0' => "签到成功",
				'r1' => "签到不可用",
				'r2' => "今日已签到",
		));
		$this->ajaxError($result['msg']);
	}
	
	/**
	 * 修改头像
	 */
	public function faceAction() {
		$this->checkLogin();
		$upload = new \Utuo\Upload();
		$info = $upload->uploadOne();
		if ( !$info ) {
			$this->ajaxError($upload->getError());
		} else {
			false !== M('User')->where("id=%d", $this->uid)->setField('face', $info['url']) and $this->ajaxSuccess("设置成功", array('url'=>$info['url']));
		}
		$this->ajaxSuccess("设置失败");
	}
	
	private function thumb($url, $maxWidth, $maxHeight) {
		$imgInfo = getimagesize(preg_replace('/http:\/\/[^\/]+/', "saestor://wmei5", $url));
		$width = $imgInfo[0];//获取图片宽度
		$height = $imgInfo[1];//获取图片高度
		$r = min($maxHeight/$height, $maxWidth/$width);
		if($r >= 1) {
			$maxHeight = $height;
			$maxWidth = $width;
		} elseif($r < 1) {
			$maxHeight = $height * $r;
			$maxWidth = $width * $r;
		}
		$temp_img = imagecreatetruecolor($maxWidth,$maxHeight); //创建画布
		$fun = str_replace('/', 'createfrom', $imgInfo['mime']);
		$im = $fun($url);
		imagecopyresized($temp_img,$im,0,0,0,0,$maxWidth,$maxHeight,$width,$height);
	
		ob_start();
		$fun = str_replace('/', '', $imgInfo['mime']);
		$fun($temp_img);
		$imgstr = ob_get_contents();
		ob_end_clean();
		imagedestroy($im);
		return $imgstr;
	}
	
}